﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Korkolaskuri
{
    class PercentageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
                      System.Globalization.CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
                                  System.Globalization.CultureInfo culture)
        {
            if (targetType == typeof(decimal)) {
                string s = value.ToString();
                if (String.IsNullOrWhiteSpace(s))
                    return 0M;
                s = s.TrimEnd(culture.NumberFormat.PercentSymbol.ToCharArray());
                decimal result = 0;
                if (decimal.TryParse(s, out result))
                    result /= 100;
                return result;
            }
            else if (targetType == typeof(double)) {
                string s = value.ToString();
                if (String.IsNullOrWhiteSpace(s))
                    return 0M;
                s = s.TrimEnd(culture.NumberFormat.PercentSymbol.ToCharArray());
                double result = 0;
                if (double.TryParse(s, out result))
                    result /= 100;
                return result;
            }
            else {
                return value;
            }
        }
    }
}
